package com.syy.compare.core;

import com.alibaba.fastjson.JSON;
import com.syy.compare.annocation.MethodCompare;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Aspect
@Component
public class MethodCompareAspect {
    @Autowired
    SpringInvoke springInvoke;

    @Around("@annotation(com.syy.compare.annocation.MethodCompare)")
    public Object aroundCompareMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取方法的入参，可以获取方法入参的注解
        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {

        }

        //获取方法上的注解
        MethodCompare methodCompare = method.getAnnotation(MethodCompare.class);

        String methodName = methodCompare.methodName();
        Class clazz = methodCompare.clazz();

        //参数序列化
        Object[] args = joinPoint.getArgs();

        Object[] newArgs = new Object[args.length];
        for (int i = 0; i < args.length; i++) {
            String argsStr = JSON.toJSONString(args[i]);
            newArgs[i] = JSON.parseObject(argsStr, args[i].getClass());
        }

        //这里可以改为异步
        Object o = springInvoke.springInvoke(clazz, methodName, newArgs);
        System.out.printf("对比方法返回值" + JSON.toJSONString(o));

        //调用原有逻辑
        Object obj = joinPoint.proceed();
        System.out.printf("原有方法返回值" + JSON.toJSONString(obj));

        return obj;

    }

}
